<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发布新文章</title>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        body{font-family: system-ui, -apple-system, Segoe UI, Roboto, "Helvetica Neue", Arial; background:#f8fafc;}
        .container{max-width: 860px;margin:40px auto;padding:20px;background:#fff;border:1px solid #e5e7eb;border-radius:12px;box-shadow:0 6px 16px rgba(0,0,0,.06)}
        h2{margin-bottom:16px;}
        .form-group{margin-bottom:12px;}
        label{display:block;margin-bottom:6px;color:#374151;font-size:14px}
        input,textarea{width:100%;padding:10px;border:1px solid #d1d5db;border-radius:8px;background:#f9fafb}
        textarea{min-height:160px}
        .row{display:grid;grid-template-columns:1fr 1fr;gap:12px}
        .actions{display:flex;gap:10px;margin-top:16px}
        .btn{padding:10px 16px;border-radius:8px;border:1px solid #d1d5db;background:#f9fafb;cursor:pointer}
        .btn-primary{background:#2563eb;color:#fff;border-color:#2563eb}
        .btn-secondary{background:#fff}
        .hint{color:#6b7280;margin-top:10px}
    </style>
    <script>
        function backToDashboard(){ window.location.href = 'dashboard.html'; }
        function saveDraft(){
            const data = collectForm();
            localStorage.setItem('article-draft', JSON.stringify(data));
            alert('草稿已保存到本地');
        }
        function collectForm(){
            return {
                title: document.getElementById('title').value || '',
                tags: document.getElementById('tags').value || '',
                categoryId: document.getElementById('categoryId').value || '',
                authorId: document.getElementById('authorId').value || '',
                content: document.getElementById('content').value || ''
            };
        }
        async function publishArticle(e){
            e && e.preventDefault();
            const form = document.getElementById('createForm');
            const fd = new FormData(form);
            try{
                const res = await fetch('articles/create', {
                    method: 'POST',
                    headers: { 'X-Requested-With': 'XMLHttpRequest' },
                    body: fd
                });
                const txt = await res.text();
                let json = {}; try{ json = JSON.parse(txt); }catch(_){ json = {}; }
                if(res.ok && json.success !== false){
                    alert('发布成功');
                    localStorage.removeItem('article-draft');
                    if(json.id){
                        window.location.href = 'articles/detail?id=' + encodeURIComponent(json.id);
                    } else {
                        window.location.href = 'articles';
                    }
                } else {
                    alert('发布失败: ' + (txt || res.status));
                }
            }catch(err){
                alert('网络错误: ' + err.message);
            }
        }
        window.addEventListener('DOMContentLoaded', function(){
            const cache = localStorage.getItem('article-draft');
            if(cache){
                try{
                    const d = JSON.parse(cache);
                    if(d.title) document.getElementById('title').value = d.title;
                    if(d.tags) document.getElementById('tags').value = d.tags;
                    if(d.categoryId) document.getElementById('categoryId').value = d.categoryId;
                    if(d.authorId) document.getElementById('authorId').value = d.authorId;
                    if(d.content) document.getElementById('content').value = d.content;
                }catch(_){}
            }
            document.getElementById('createForm').addEventListener('submit', publishArticle);
        });
    </script>
</head>
<body>
<div class="container">
    <h2><i class="fa fa-pencil"></i> 发布新文章</h2>
    <form id="createForm" method="post" action="articles/create">
        <div class="form-group">
            <label for="title">标题</label>
            <input id="title" name="title" required placeholder="请输入文章标题" />
        </div>
        <div class="form-group">
            <label for="tags">标签（用逗号分隔）</label>
            <input id="tags" name="tags" placeholder="示例：Java,Web,教程" />
        </div>
        <div class="row">
            <div class="form-group">
                <label for="categoryId">分类ID（可选）</label>
                <input id="categoryId" name="categoryId" type="number" min="1" placeholder="例如：1" />
            </div>
            <div class="form-group">
                <label for="authorId">作者ID（可选）</label>
                <input id="authorId" name="authorId" type="number" min="1" placeholder="例如：1" />
            </div>
        </div>
        <div class="form-group">
            <label for="content">内容</label>
            <textarea id="content" name="content" required placeholder="支持HTML片段，例如：<p>正文内容</p>"></textarea>
        </div>
        <div class="actions">
            <button type="button" class="btn" onclick="saveDraft()">保存草稿</button>
            <button type="submit" class="btn btn-primary">立即发布</button>
            <button type="button" class="btn btn-secondary" onclick="backToDashboard()">返回工作台</button>
        </div>
    </form>
    <p class="hint">提示：分类ID与作者ID为可选项，未填写时后端会按默认逻辑处理。保存草稿仅保存在浏览器本地。</p>
</div>
</body>
</html>